package com.tg.app.activity.base;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextPaint;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.appbase.custom.constant.CommonConstants;
import com.base.BaseActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.ListPreloader;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader;
import com.bumptech.glide.util.FixedPreloadSizeProvider;
import com.google.android.material.navigation.NavigationView;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StatusBarUtil;
import com.tg.app.R;
import com.tg.app.activity.device.MultiPlayerActivity;
import com.tg.app.activity.device.list.DeviceListPushConfig;
import com.tg.app.adapter.DeviceAdapter;
import com.tg.app.adapter.DeviceListAdapter;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.util.LogUtils;
import com.tg.app.view.grid.CirclePageIndicator;
import com.tg.app.view.grid.GridPagerSnapHelper;
import com.tg.app.widget.CommItemDecoration;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.business.IMessageModule;
import com.tg.data.bean.DeviceItem;
import com.tg.data.http.entity.MessageDataBean;
import com.tg.message.msg.MessageActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;


public abstract class DeviceListBaseActivity extends BaseActivity implements DeviceListPushConfig,
        View.OnClickListener, DeviceAdapter.OnItemClickListener,DeviceAdapter.OnDoorbellLoadListener, DeviceAdapter.OnNoItemClickListener, NavigationView.OnNavigationItemSelectedListener {


    protected ImageButton drawMenu, btnCardAdd, btnListAdd, btnDisplayChanged;
    protected DeviceAdapter mAdapter;
    protected SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayout emptyLayout;
    protected RecyclerView recyclerView;
    protected CopyOnWriteArrayList<DeviceItem> deviceList = new CopyOnWriteArrayList<>();
    private CirclePageIndicator pageIndicator;
    private GridPagerSnapHelper gridPagerSnapHelper;
    private static final int imageWidthPixels = 640;
    private static final int imageHeightPixels = 360;

    private PopupWindow mMoreWindow;
    private LinearLayoutManager linearLayoutManager;
    protected boolean isLocalList = false;
    protected boolean isListDisplay = false;

    protected DrawerLayout mDrawerLayout;
    private int statusBarHeight;
    protected  HashMap<String,MessageDataBean> mDoorbellMaps = new HashMap<>();

    protected int devicePage = 1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_tange_device_list);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setNavigationBarColor(Color.WHITE);
        }
        hideActionBar();
        getStatusBarHeight();
        initView();
        swipeRefreshLayout = findViewById(R.id.swipe);
        swipeRefreshLayout.setRefreshing(true);
        mDrawerLayout = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawerLayout, null, R.string.open_gps_service_content, R.string.open_gps_service_content);
        toggle.syncState();

        initNavigationView();

        StatusBarUtil.setStatusBarTransparent(this);
        createPath();
        swipeRefreshLayout.setOnRefreshListener(this::getCameraList);
        getCameraList();


    }

    private void getStatusBarHeight() {
        statusBarHeight = (int) getResources().getDimension(R.dimen.status_bar_height);
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
    }

    private void initNavigationView() {

    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    protected void listAdapter() {
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mAdapter = new DeviceListAdapter(this, deviceList);
        mAdapter.setDoorbellMaps(mDoorbellMaps);
        mAdapter.setHasStableIds(true);
        mAdapter.setOnItemClickListener(this, this);

        recyclerView.setAdapter(mAdapter);
        recyclerView.setLayoutManager(linearLayoutManager);
        pageIndicator.setVisibility(View.GONE);
        if (gridPagerSnapHelper != null) {
            gridPagerSnapHelper.attachToRecyclerView(null);
        }
        isListDisplay = true;
    }

    protected void initView() {
        RelativeLayout viewLayout = findViewById(R.id.rl_devicelist_toolbar);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewLayout.getLayoutParams();
        params.topMargin = statusBarHeight;
        viewLayout.setLayoutParams(params);
        drawMenu = findViewById(R.id.draw_menu);
        btnDisplayChanged = findViewById(R.id.btn_device_list_display);
        recyclerView = findViewById(R.id.recycle);
        linearLayoutManager = new LinearLayoutManager(this);

        ListPreloader.PreloadSizeProvider sizeProvider = new FixedPreloadSizeProvider(imageWidthPixels, imageHeightPixels);
        ListPreloader.PreloadModelProvider modelProvider = new MyPreloadModelProvider();
        RecyclerViewPreloader preloaded = new RecyclerViewPreloader<>(Glide.with(this), modelProvider, sizeProvider, 10 /*maxPreload*/);
        recyclerView.addOnScrollListener(preloaded);
        ((DefaultItemAnimator) Objects.requireNonNull(recyclerView.getItemAnimator())).setSupportsChangeAnimations(false);

        recyclerView.addItemDecoration(CommItemDecoration.createVertical(Color.TRANSPARENT, DimenUtil.dp2px(this, 10)));

        btnListAdd = findViewById(R.id.btn_device_list_item_add_list);
        btnCardAdd = findViewById(R.id.btn_device_list_item_add_card);
        emptyLayout = findViewById(R.id.lin_device_list_empty_add);
        pageIndicator = findViewById(R.id.rv_rvg_pager_indicator);
        if (deviceList != null && deviceList.size() > 0) {
            pageIndicator.setPageColumn(deviceList.size());
        }
        btnListAdd.setOnClickListener(this);
        btnCardAdd.setOnClickListener(this);
        drawMenu.setOnClickListener(this);

        btnDisplayChanged.setOnClickListener(v -> {
            uploadLog("listDisplay");
            listDisplay(!isListDisplay);
        });

        buildAdpater();
        pageIndicator.setRecyclerView(recyclerView);
    }

    protected abstract void buildAdpater();

    protected void listDisplay(boolean isList) {
        isListDisplay = isList;
        if (isList) {
            btnDisplayChanged.setImageResource(R.drawable.ic_tange_global_icon_by_row_list);
            listAdapter();
        }
        PreferenceUtil.setBoolean(getBaseContext(), CommonConstants.PRE_DEVICE_LIST_SHOW, isList);
        if (deviceList.size() == 0) {
            emptyDisplay(isList);
        }
    }

    protected void emptyDisplay(boolean isList) {
        pageIndicator.setVisibility(View.GONE);
        if (isList) {
            btnListAdd.setVisibility(View.VISIBLE);
            btnCardAdd.setVisibility(View.GONE);
        } else {
            btnListAdd.setVisibility(View.GONE);
            btnCardAdd.setVisibility(View.VISIBLE);
        }
    }

    public abstract void getCameraList();

    public void updateUI() {
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        swipeRefreshLayout.setRefreshing(false);
        if (deviceList.size() > 0) {
            mAdapter.notifyDataSetChanged();
            pageIndicator.notifyDataSetChanged();
            recyclerView.setVisibility(View.VISIBLE);
            emptyLayout.setVisibility(View.GONE);
            if (!isListDisplay) {
                pageIndicator.setVisibility(View.VISIBLE);
            } else {
                pageIndicator.setVisibility(View.GONE);
            }


        } else {
            recyclerView.setVisibility(View.GONE);
            emptyLayout.setVisibility(View.VISIBLE);

        }
    }

    @Override

    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.draw_menu) {
            onBackClick();
        }  else if (id == R.id.btn_device_list_item_add_list || id == R.id.btn_device_list_item_add_card) {
            onViewClick();
        } else if (id == R.id.rl_nav_header_exit_sdk || id == R.id.rl_nav_header_account || id == R.id.rl_nav_header_tool || id == R.id.rl_nav_header_help || id == R.id.rl_nav_header_about || id == R.id.rl_nav_header_logout) {
            onNavViewClick(v);
        }
    }

    protected abstract void onBackClick();

    protected void onNavViewClick(View v) {

    }

    @Override
    public abstract void onItemClick(int position, int type);

    @Override
    public void onUpdate() {
        getCameraList();
    }


    /**
     * 打开一个设备，看视频
     */
    protected void openDevice(DeviceItem device, int type) {
        DeviceHelper.openDevice(this, device, type);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void openMoreFuncPopWindow() {
        if (mMoreWindow == null) {
            View contentView = LayoutInflater.from(this).inflate(R.layout.layout_popwindow_device_list_more, null);
            mMoreWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            mMoreWindow.setOutsideTouchable(true);
            mMoreWindow.setFocusable(true);

        }
        View contentView = mMoreWindow.getContentView();

        ImageView imageView = contentView.findViewById(R.id.btn_icon_device_list_more_screen);
        TextView textView = contentView.findViewById(R.id.tv_icon_device_list_more_screen);
        ImageView displayImage = contentView.findViewById(R.id.btn_icon_device_list_more_display);
        TextView displayText = contentView.findViewById(R.id.tv_icon_device_list_more_display);

        contentView.findViewById(R.id.btn_icon_device_list_more_add).setOnClickListener(v -> addDevice());
        contentView.findViewById(R.id.tv_icon_device_list_more_add).setOnClickListener(v -> addDevice());
        if (isLocalList) {

            contentView.findViewById(R.id.card_mode_layout).setVisibility(View.GONE);
            contentView.findViewById(R.id.more_screen_layout).setVisibility(View.GONE);

            textView.setVisibility(View.GONE);
            imageView.setVisibility(View.GONE);
            displayImage.setVisibility(View.GONE);
            displayText.setVisibility(View.GONE);
        } else {

            contentView.findViewById(R.id.card_mode_layout).setVisibility(View.VISIBLE);
            contentView.findViewById(R.id.more_screen_layout).setVisibility(View.VISIBLE);

            if (!isListDisplay) {
                displayImage.setImageResource(R.drawable.ic_tange_global_pop_list_mode);
                displayText.setText(R.string.more_display_list);
            } else {
                displayImage.setImageResource(R.drawable.ic_tange_global_pop_card_mode);
                displayText.setText(R.string.more_display_card);
            }
            View.OnClickListener screenListener = v -> {
                goToMultiPlayerActivity();
                mMoreWindow.dismiss();
                uploadLog("more_multiplay");
            };
            View.OnClickListener displayListener = v -> {
                listDisplay(!isListDisplay);
                mMoreWindow.dismiss();
                uploadLog("more_display");

            };

            imageView.setOnClickListener(screenListener);
            textView.setOnClickListener(screenListener);
            displayImage.setOnClickListener(displayListener);
            displayText.setOnClickListener(displayListener);
        }

        setMoreWindowLocation();
    }

    private void setMoreWindowLocation() {
    }

    private int getMaxWidth(){
        View contentView = mMoreWindow.getContentView();
        TextView textView = contentView.findViewById(R.id.tv_icon_device_list_more_screen);
        TextView displayText = contentView.findViewById(R.id.tv_icon_device_list_more_display);
        TextView addText = contentView.findViewById(R.id.tv_icon_device_list_more_add);
        int maxWidth = 0;
        TextPaint paint = textView.getPaint();
        Rect bounds = new Rect();

        String text = textView.getText().toString().trim();
        paint.getTextBounds(text,0, text.length(),bounds);
        maxWidth = Math.max(maxWidth, bounds.width());
        TGLog.d("width = " + maxWidth);

        text = displayText.getText().toString().trim();
        paint.getTextBounds(text,0,text.length(),bounds);
        maxWidth = Math.max(maxWidth, bounds.width());
        TGLog.d("width = " + maxWidth);

        text = addText.getText().toString().trim();
        paint.getTextBounds(text,0,text.length(),bounds);
        maxWidth = Math.max(maxWidth, bounds.width());
        maxWidth += DimenUtil.dp2px(TGApplicationBase.getApplicationContext(), 5);
        TGLog.d("width = " + maxWidth);
        return maxWidth;
    }

    private void goToMultiPlayerActivity() {
        Intent listIntent = new Intent(getBaseContext(), MultiPlayerActivity.class);
        ArrayList<DeviceItem> items = new ArrayList<>(deviceList);
        listIntent.putParcelableArrayListExtra(MultiPlayerActivity.EXT_DEVICE_TTEMS, items);
        startActivity(listIntent);
    }

    private void addDevice() {
        onViewClick();
        mMoreWindow.dismiss();
        uploadLog("more_adddevice");
    }

    @Override
    public abstract void onViewClick();


    private void createPath() {
        String path = Environment.getExternalStorageDirectory().getPath();
        String fileName = path + File.separator + getString(R.string.app_name);
        File f = new File(fileName);
        if (!f.exists()) {
            f.mkdirs();
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getCameraList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    protected void onStop() {
        super.onStop();
        dismissMoreWindow();
    }

    private void dismissMoreWindow() {
        if (mMoreWindow != null && mMoreWindow.isShowing()) {
            mMoreWindow.dismiss();
        }
    }

    protected void uploadLog(String btn) {
        LogUtils.onEventClickByName("device_list", btn);
    }


    private class MyPreloadModelProvider implements ListPreloader.PreloadModelProvider<String> {


        @NonNull
        @Override
        public List<String> getPreloadItems(int position) {
            if (position < deviceList.size()) {
                String url = deviceList.get(position).image_path;
                return Collections.singletonList(url);
            }
            return Collections.emptyList();
        }

        @Nullable
        @Override
        public RequestBuilder<?> getPreloadRequestBuilder(@NonNull String item) {
            return Glide.with(getBaseContext()).load(item);
        }
    }
}
